import json
import re

from django.http import HttpResponseForbidden, HttpResponse, HttpResponseBadRequest, JsonResponse
from django.shortcuts import render
from django.views import View
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha


class ImgCodeView(View):
    def get(self, request):
        """生成图片验证码返回给前端"""

        # 获取参数
        cur = request.GET.get('cur')
        pre = request.GET.get('pre')

        # 数据校验
        if not cur:
            return HttpResponseBadRequest('missing argument')

        # 生成图形验证码
        text, image = captcha.generate_captcha()

        # 将验证码信息写入redis
        redis_client = get_redis_connection('verify')
        redis_client.setex('img_code_%s' % cur, 60, text)

        return HttpResponse(image, content_type='image/jpeg')


class SmsCodeView(View):
    def post(self, request):
        """获取短信验证码"""

        # 获取数据
        mobile = json.loads(request.body).get('mobile')
        id = json.loads(request.body).get('id')
        text = json.loads(request.body).get('text')

        # 校验数据
        if not all([mobile, id, text]):
            return HttpResponseBadRequest('missing argument')

        if not re.match(r'1[3568]\d{9}$', mobile):
            return HttpResponseBadRequest('illegal mobile')

        redis_client = get_redis_connection('verify')
        img_text = redis_client.get('img_code_%s' % id)

        if img_text:
            img_text = img_text.decode()

        if text != img_text.lower():
            return HttpResponseBadRequest('error image code')

        # 验证是否频繁发送
        if redis_client.get('sms_flag_%s' % mobile):
            return HttpResponseBadRequest('frequent request')

        # 生成随机码
        from random import randint
        sms_code = '%06d' % randint(0, 999999)
        print(sms_code)

        # 使用容联云通讯发送短信
        # ccp = CCP()
        # result = ccp.send_template_sms(mobile, [sms_code, 5], 1)
        # from main import send_sms_code
        # send_sms_code.delay(mobile, sms_code)

        # 写入数据库
        redis_client.setex('sms_code_%s' % mobile, 300, sms_code)
        redis_client.setex('sms_flag_%s' % mobile, 60, 1)

        # 返回响应
        res = {
            'errno': 0,
            'errmsg': '发送成功'
        }
        return JsonResponse(res, status=201)

